<template>
    <Layout>
        <div v-if="!detailShow && !progressShow" v-show="!detailShow && !progressShow">
            <Form ref="form1" :model="dataToQuery" :label-width="120">
                <Row class="query-form">
                    <Col span="8">
                        <FormItem label="二级集团：">
                            <two-level-org org-code class="query-form-el" v-model="dataToQuery.twoLevelOrgCode" />
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="单位名称：" prop="companyId">
                            <company-select v-model="dataToQuery.companyName" style="width:100%" />
                            <!-- <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgname='setQueryOrgName'
                                          :orgTree="true"
                                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom> -->
                        </FormItem>
                    </Col>
                    <Col span="8" v-if="!switchFlag">
                        <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                        <Button @click="reset" class="ivu-btn-reset">重置</Button>
                        <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                    </Col>
                    <Col span="8" v-else>
                        <FormItem label='考核序号：' prop='unitNo'>
                            <Input class='query-form-el' placeholder="请填写考核序号" type='text' v-model='dataToQuery.unitNo'></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row v-show="switchFlag" class="query-form">
                    <Col span="8">
                        <FormItem label="年度：" prop="year1" >
                            <DatePicker class="query-form-el" type="year" placeholder="请选择年度" v-model="dataToQuery.year1" :clearable="false"
                                        @on-change="()=>{if(dataToQuery.year1 instanceof Date){dataToQuery.year = dataToQuery.year1.getFullYear().toString()}}"></DatePicker>
                        </FormItem>
                    </Col>
                    <!-- <Col span="8">
                        <FormItem label="任务书类型：" prop="assessmentType">
                            <Select v-model='dataToQuery.assessmentType' clearable class="query-form-el" placeholder="请选择任务书类型">
                                <Option v-for="item in dicMap.assessmentTypes" :value="item.code" :key="item.code">{{item.name }}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col> -->
                    <Col span="8" offset="8">
                        <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                        <Button @click="reset" class="ivu-btn-reset">重置</Button>
                        <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                    </Col>
                </Row>
                <Row class="query-form">
                    <Col span="24">
                        <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                        <Button size="large" class="ivu-btn-add" icon="md-download"  @click="download">下载导入模板</Button>
						<Button size="large" class="ivu-btn-add" :disabled='selectId && !buttonDisabled' icon="md-cloud-upload"  @click="uploadAcc">导入任务书</Button>
                        <Button size="large" class="ivu-btn-add" icon="md-cloud-download" :loading="exportLoading" @click="exportExcel">导出任务书</Button>
                    </Col>
                </Row>
            </Form>
            <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" :loading='pageStatus.loading'
                @on-sort-change="sortChange" border :columns="columns1" :data="dataTable">
                <template slot-scope="{ row, index }" slot="select">
                    <Radio v-model="row.selectCheck" @on-change="handleRowChange(row)" >{{ "" }}</Radio>
                </template>
            </Table>
            <Row style="margin-right:10px;">
                <Col span="24">
                    <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                          @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                          show-total show-sizer show-elevator/>
                </Col>
            </Row>
            <Modal :title="this.getModalTitle('任务书在线分解')" :transfer=false :mask-closable="false" v-model="dialogShow"
               v-if="dataToView && dialogShow" :width=800 class-name='limit-height-dialog'>
                <Row>
                    <Col span="24">
                        <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false"
                              :model="dataToView" :rules="mode === 'view'?{}:ruleCustom"
                              :label-width="mode === 'view'?160:null" :label-position="mode === 'view'?'right':'top'">
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="11">
                                    <FormItem label='单位名称：' prop='companyId'>
                                        <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                                        <div v-else>
                                            <cascader-dom  v-if="show"  class='query-form-el' ref='orgCascader' @setOrgInfo='setCompanyId1'  :orgTree="true"
                                                           :currentOrgId="dataToView.companyId"
                                                           :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}" ></cascader-dom>
                                        </div>
                                    </FormItem>
                                </Col>
                                <Col span="11" >
                                    <FormItem label="年度：" prop="yearDate" >
                                        <div v-if="mode === 'view'">{{dataToView.year}}</div>
                                        <DatePicker v-else class='query-form-el' type="year" placeholder="请输入" v-model="dataToView.yearDate" :clearable="false"></DatePicker>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="11">
                                    <FormItem label='考核序号：' prop='unitNo'>
                                        <div v-if="mode === 'view'">{{ dataToView.unitNo }}</div>
                                        <Input v-else class='query-form-el' placeholder="请填写考核序号" disabled type='text' v-model='dataToView.unitNo'></Input>
                                    </FormItem>
                                </Col>
                                <Col span="11">
                                  <!-- <FormItem label="任务书类型：" prop="assessmentType">
                                        <div v-if="mode === 'view'">{{dataToView.assessmentType=='1'?'安全':dataToView.assessmentType=='2'?'环保':''}}</div>
                                        <Select v-model='dataToView.assessmentType' class='query-form-el' placeholder="请选择任务书类型" v-else>
                                            <Option v-for="item in dicMap.assessmentTypes" :value="item.code" :key="item.code">{{item.name }}
                                            </Option>
                                        </Select>
                                    </FormItem> -->
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="23">
                                    <FormItem v-if="mode === 'view'" label="任务书签订附件：">
                                        <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles">
                                            <a @click="downloadFiles(item,index)"><span style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                                            <Progress v-show="uploadListVisible[item.id]" :percent="uploadListPercent[index]"></Progress>
                                        </div>
                                    </FormItem>
                                    <FormItem v-else label="任务书签订附件：" prop="idFiles">
										<Alert type="error">上传处级单位与集团签订的正式任务书扫描件。</Alert>
                                        <div>
                                            <Upload ref="upload"
                                                    :before-upload="(file) => { beforeUpload1(file, 'id', 'taskBook') }"
                                                    :show-upload-list="true"
                                                    :max-size="10240"
                                                    type="drag"
                                                    :action="fileUrl">
                                                <div style="padding: 10px">
                                                    <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                                    <p>点击将文件拖拽到这里上传</p>
                                                    <!--<span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>-->
                                                </div>
                                            </Upload>
                                        </div>
                                        <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles"
                                             :key='item'>
                                            <a @click="downloadFiles(item,index)">{{ item.fileName }}</a>
                                            <Button type="text" icon="md-trash" @click="removeFile1(item.id, 'id', 'taskBook')" style="margin-left: 5px;margin-bottom: 3px"/>
                                            <Progress v-show="uploadListVisible[item.id]" :percent="uploadListPercent[index]"></Progress>
                                            <!--<Progress  v-show="filePercentVisible[index]" :percent="filePercent[index]"></Progress>-->
                                        </div>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="11">
                                    <FormItem label='填报人：' prop='createUserName'>
                                        <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                        <Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly
                                               v-model='dataToView.createUserName'></Input>
                                    </FormItem>
                                </Col>
                                <Col span="11">
                                    <FormItem label='填报时间：' prop='createDate'>
                                        <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                        <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                                                    v-model='dataToView.createDate'></DatePicker>
                                    </FormItem>
                                </Col>
                            </Row>

                        </Form>
                    </Col>
                </Row>
                <div slot="footer">
                    <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
                    <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
                    <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
                </div>
            </Modal>

            <Modal title="完成情况" :transfer=false :mask-closable="false" v-model="model1" :width=700 class-name='limit-height-dialog' @on-cancel="onCancel">
                <Form ref="dialogForm" :show-message="false" :model="dataToView"
                      :label-width="mode === 'view'?160:null" :label-position="mode === 'view'?'right':'top'">
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="23">
                            <FormItem label='上半年完成情况：' prop='performanceOne'>
                                <Input class='query-form-el' placeholder="请填写上半年完成情况" type='textarea' :disabled="!buttonDisabled" show-word-limit :maxlength="500"
                                       v-model='dataToView.performanceOne'></Input>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="23">
                            <FormItem label="下半年完成情况：" prop="performanceTwo">
                                <Input class='query-form-el' placeholder="请填写下半年完成情况" type='textarea' :disabled="!buttonDisabled" show-word-limit :maxlength="500"
                                       v-model='dataToView.performanceTwo'></Input>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div slot="footer">
                    <Button v-if="buttonDisabled" type="primary" class='ivu-btn-save' @click="submit1('dialogForm')">确定</Button>
                    <Button v-if="buttonDisabled" type="primary" class='ivu-btn-cancel' @click="onCancel">取消</Button>
                    <Button v-if="!buttonDisabled" class='ivu-btn-save' @click="onCancel">关闭</Button>
                </div>
            </Modal>


            <Modal title="上报" :transfer=false :mask-closable="false" v-model="model3" :width=500 :styles="{height:'400px'}" @on-cancel="model3=false">
                <Form :show-message="false" :model="dataToView" :label-width="100">
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="23">
                            <FormItem label='审批人：' prop='applyUserId'>
                                <Select v-if="show" v-model='dataToView.applyUserId' placeholder="请选择审批人" class='query-form-el'>
                                    <Option v-for="item in dictMap[dataToView.assessmentType==1?'saAppUserids':'enAppUserids']" :value="item.userId" :disabled="item.disabled" :label="item.userName" :key="item.userId">
                                        <span>{{item.userName }}</span>
                                        <span style="float:right;color:#ccc">{{item.companyName }}</span>
                                    </Option>
                                </Select>
                            </FormItem>
                        </Col>
						<Col span="23">
						  <Alert type="error">审批人来自二级集团{{dataToView.assessmentType==1?'安全':'环保'}}管理人员角色。</Alert>
						</Col>
                    </Row>
                </Form>
                <div slot="footer">
                    <Button type="primary" class='ivu-btn-save' @click="reportInfo(dataToView)">确定</Button>
                    <Button type="primary" class='ivu-btn-cancel' @click="model3=false">取消</Button>
                </div>
            </Modal>

            <Modal :transfer=false v-model="model4"  :width=900>
                <Tabs>
                    <TabPane label="历史记录">
                        <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0" :loading="loading2"
                               :data="history" width="100%"  :height="450" highlight-row stripe size="small"></Table>
                    </TabPane>
                    <TabPane label="流程图">
                        <div style="height: 450px; overflow-y: auto; overflow-x: auto">
                            <img :src="imgUrl" >
                        </div>
                    </TabPane>
                </Tabs>
                <div slot="footer">
                    <Button @click="model4=false" class="ivu-btn-save">关闭</Button>
                </div>
            </Modal>

            <Modal :mask-closable="false" :transfer=false  v-model="uploadEdit" :width=700 :title="this.taskBookName+'导入'" @on-cancel="close">
                <Form  ref="map" :show-message="false" :model="map" label-position="top">
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="23">
                            <FormItem  label="" prop="file">
                                <div>
                                    <Upload ref="upload1"
                                            :before-upload="handleUpload "
                                            :format="['xlsx', 'xls']"
                                            accept=".xlsx, .xls"
                                            :max-size="10240"
                                            type="drag"
                                            :action="''">
                                        <div style="padding: 10px">
                                            <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                            <p>点击将文件拖拽到这里上传</p>
                                            <span style="font-size:8px;color: #797a64">仅支持上传单个excel </span>
                                        </div>
                                    </Upload>
                                </div>
                                <div v-if="fileTrue">
                                    <a>{{ map.file.name }}</a>
                                    <Button type="text" icon="md-trash" @click="map.file = {},fileTrue = false" style="margin-left: 5px;margin-bottom: 3px"/>
                                </div>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div slot="footer">
                    <Button type="primary" class='ivu-btn-save' :disabled="uploadDissabled" @click="submitFile('map')">确定</Button>
                    <Button type="primary" class='ivu-btn-cancel' @click="close1">取消</Button>
                </div>
            </Modal>

            <Modal title="导入详情" v-model="logInfoModel" :transfer=false :mask-closable="false">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <div v-html="logInfo"></div>
                    </Col>
                </Row>
                <div slot="footer">
                    <Button type="primary" class='ivu-btn-cancel' @click="logInfoModel=false,logInfo=null">关闭</Button>
                </div>
            </Modal>
        </div>

        <task-book-list v-if="detailShow" :show="detailShow"
                :taskBook="dataToView" :buttonDisabled="buttonDisabled"
                @close="close"/>

        <task-book-progress v-if="progressShow" :show="progressShow"
                            :taskBook="dataToView"
                            :view="false"
                            @close="close"/>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {formatDate} from '@/tools/index'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import taskBookList from './taskBookList'
    import taskBookProgress from './taskBookProgress'

    export default {
        components: {cascaderDom,taskBookList,taskBookProgress},
		computed: {
		    isResult() {
		        return this.$route.name
		    }
		},
        data() {
            return {
                ...this.createCommonDataField(),
                columns1: [
                    {slot: 'select', title: '', width: 60, align: 'center', fixed: 'left'},
                    {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    {
                        title: '状态',
                        align: 'center',
                        fixed:'left',
                        key: 'status',
                        width: 100,
                        render: (h, params) => {
                            let color = 'green';
                            if (params.row.procinstState == undefined || params.row.procinstState == null || params.row.procinstState == 2) {
                                color = 'red';
                            }
                            if (params.row.procinstState == 1) {
                                color = 'blue';
                            }
                            return h('div', [
                                h('span', {
                                    style: {
                                        color: color
                                    }
                                }, params.row.procinstState == 1 ? '审批中' : params.row.procinstState == 2 ? '审批退回' : params.row.procinstState == 3 ? '审批通过' : '未上报' || '--')
                            ]);
                        }
                    },
                    { key:'unitNo',title: '考核序号',  align: 'center', minWidth: 100,  },
                    { key:'companyName',title: '单位名称',  align: 'center', minWidth: 200, },
                    { key:'year',title: '年份',  align: 'center', minWidth: 90, },
                    // { key:'assessmentType',title: '任务书类型',  align: 'center', minWidth: 100, render: (h, params) => {
                    //         return h('span', params.row.assessmentType == '1' ? '安全' : params.row.assessmentType == '2' ? '环保' : '');}},
                    { key:'progress',title: '扣分',  align: 'center', minWidth: 80},
										{ key:'scoreDesc',title: '扣分描述',  align: 'center', minWidth: 100,tooltip:true},
                    {title: '录入时间', minWidth: 100, sortable: "custom",align: 'center', key:'createDate', render: this.renderCellDate},
                    {title: '录入人', minWidth: 100, align: 'center', key:'createUserName'},
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 300,
                        align: 'center',
                        render: (h, params) => {
                            const enable = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId === '73b38b37dff64392ba0ee7dd579bf293') !== undefined
                                ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined;
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',},
                                    on: {
                                        click: () => {
                                            this.viewData(params);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {
                                        fontSize: '14px',
                                        color: (params.row.procinstState !=1 && params.row.procinstState !=3) && enable ? '' : '#c5c8ce',
                                        pointerEvents: (params.row.procinstState !=1 && params.row.procinstState !=3) && enable ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.editData(params);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.detailShow = true
                                            this.buttonDisabled = (params.row.procinstState !=1 && params.row.procinstState !=3) && enable
                                            this.dataToView = {...params.row}
                                        }
                                    }
                                }, '分解'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {
                                        fontSize: '14px',
                                        color: !params.row.procinstState && enable ? '' : '#c5c8ce',
                                        pointerEvents: !params.row.procinstState && enable ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.getRoleUsers(params.row)
                                            this.dataToView = {...params.row}
                                            this.dataToView.applyUserId = undefined
                                        }
                                    }
                                }, '上报'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.procinstState==3 && enable ? '' : '#c5c8ce',
                                        pointerEvents: params.row.procinstState==3 && enable ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.progressShow = true
                                            this.dataToView = {...params.row}
                                        }
                                    }
                                }, '更新进展'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
								h('A', {
								    props: {type: 'primary', size: 'small'},
								    style: {
								        fontSize: '14px',
								        color: (params.row.procinstState !=1 && params.row.procinstState !=2 && params.row.procinstState !=3) && enable ? 'red' : '#c5c8ce',
								        pointerEvents: (params.row.procinstState !=1 && params.row.procinstState !=2 && params.row.procinstState !=3) && enable ? '' : 'none'
								    },
								    on: {
								        click: () => {
								            this.deleteData(params);
								        }
								    }
								}, '删除'),
								h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.procinstState==3 ? '' : '#c5c8ce',
                                        pointerEvents: params.row.procinstState==3 ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.buttonDisabled = params.row.procinstState ==3 && enable
                                            this.dataToView = {...params.row}
                                            this.mode = 'edit'
                                            this.model1 = true
                                        }
                                    }
                                }, '执行情况'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('a', {
                                    props: {
                                        type: 'primary',
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.procinstId == null ? '#d0d0d0' : '',
                                        pointerEvents: params.row.procinstId == null ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                            this.showHistory(params.row);
                                        }
                                    }
                                },'审批记录')
                            ]);
                        }
                    }
                ],
                ruleCustom: {
                    companyId: [ { required: true, message: '请填写单位名称', trigger: 'change',}],
                    yearDate: [{ required: true, message: '请选择年份', trigger: 'blur',type:'date' }],
                    unitNo: [ { required: true, message: '请填写考核序号', trigger: 'change',}],
                    assessmentType: [ { required: true, message: '请选择任务书类型', trigger: 'change',}],
                    idFiles: [{
                        validator: (rule, value, callback) => {
                            if (this.dataToView.idFiles.length < 1) {
                                callback('附件必须上传')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }]
                },
                tableHeight: 10,
                dicMap: {
                    assessmentTypes: [{code: '1', name: '安全'}, {code: '2', name: '环保'}],
                },
                // api
                queryUrl: Api.queryTaskBook,
                exportUrl: Api.exportTaskBook,
                deleteUrl: Api.deleteTaskBook,
                updateUrl: Api.updateTaskBook,
                saveUrl: Api.saveTaskBook,
                show:true,
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),

                detailShow:false,
                buttonDisabled:false,

                progressShow:false,

                model1: false,
                idFiles:[],
                id:'',

                selectId: '',
                uploadEdit: false,
                map:{},
                fileTrue:false,
                uploadDissabled:false,
                logInfoModel:false,
                logInfo:null,
                taskBookName: '',
                exportLoading: false,

                dictMap:{},
                model3: false,
                imgUrl:'',
                history:[],
                model4:false,
                loading2:false,
                columns2: [
                    {type: 'index', title: '序号', width: 80, align: 'center',},
                    {width: 180, title: '审批时间', key: 'endTime', align: 'center',},
                    {width: 185, title: '节点名称', key: 'name', align: 'center',},
                    {width: 120, title: '审批人', key: 'userName', align: 'center'},
                    {width: 100, title: '审批意见', key: 'route', align: 'center'},
                    {width: 200, title: '备注', key: 'opinions', align: 'center'},
                ],
            }
        },
        async mounted() {
            this.setTableHeight();
            this.dataToQuery.year1 = new Date()
            this.dataToQuery.year = new Date().getFullYear().toString()
            this.query();
        },
        methods: {
            ...pageCommonFunction,
            close(flag){
                this.detailShow = false
                this.buttonDisabled=false
                this.progressShow = false
                // if (flag) {
                    this.query()
                // }
            },

            deleteData(params) {
                this.deleteDateAjax(params);
            },
           
            query() {
				// 1 安全 2环保
			    this.dataToQuery.assessmentType = this.isResult =='taskBook' ?'2':'1'
                this.queryAjax();
                this.dataTable.forEach(m=>m.selectCheck=false)
                this.selectId = undefined
            },

           async setCompanyId1(data) {
                if (data && data instanceof Array && data.length > 0) {
					await this.queryUnitNo(data[data.length - 1])
                    this.$set(this.dataToView, 'companyId', data[data.length - 1])
                    // if(this.$refs.dialogForm) this.$refs.dialogForm.validateField('companyId')
                }
            },
			async queryUnitNo(companyId) {
			    let data = {
			        startPage: 1,
			        size: 2,
			        conditions: {
						companyId:companyId
					}
			    };
			    this.$http.post(Api.companyDirectorList, data).then((res) => {
			        if (res.data.status === 201) {
						this.$set(this.dataToView, 'unitNo', '')
			            this.$Message.error('考核单元获取异常');
			        }
			        if (res.data.data.data.length > 0) {
			        	this.$set(this.dataToView, 'unitNo', res.data.data.data[0].companyNum)
			        } else {
						this.$set(this.dataToView, 'unitNo', '')
						this.$Message.error('尚未维护考核单元，请先维护后在添加任务书');
					}
			    }).catch(e => {
					this.$set(this.dataToView, 'unitNo', '')
			        this.$Message.error("考核单元获取异常")
			    })
			},
            async afterDataToAddInit() {
                await this.queryUnitNo(this.dataToView.companyId);
            },
			
            createEmptyDataToAdd() {
                return {
                    createDate: new Date(),
                    createUserId: this.currentUser.userId,
                    createUserName: this.currentUser.userName,
                    mobileNumber:this.currentUser.mobileNumber,
                    yearDate:new Date(),
                    id: this.get_uuid(),
					assessmentType: this.isResult =='taskBook' ?'2':'1',
                    idFiles: [],

                }
            },
			submit(name) {
			    if(this.dataToView.yearDate) {
			        this.dataToView.year = this.dataToView.yearDate.getFullYear();
			    }
			    this.submitAjax(name);
			},
            async beforeEditDialogOpen(data) {
                data.row.yearDate = new Date(data.row.year + '-01-01');
            },
            async afterDataToViewInit() {
                await this.getFiles1('id', 'taskBook');
            },


            handleRowChange(data) {
                const enable = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === data.createUserId || this.currentUser.userRole.find(obj => obj.roleId === '73b38b37dff64392ba0ee7dd579bf293') !== undefined || this.currentUser.userBeHandedOver.find(obj => obj == data.createUserId) != undefined;
                this.buttonDisabled =  (data.procinstState !=1 && data.procinstState !=3) && enable
                this.taskBookName = data.companyName +'任务书'
                this.selectId = data.id
                this.dataTable.splice()
                this.dataTable.forEach(m=>{
                    m.selectCheck=false
                    if (data.id === m.id) {
                        m.selectCheck=true
                    }
                })
            },
            handleUpload (file) {
                this.map.file = file;
                this.fileTrue = true
                return false;
            },
            submitFile(map){
                if (this.fileTrue == false) {
                    return this.$Message.error("附件不能为空");
                }
                this.$refs[map].validate((valid) => {
                    if (valid) {
                        this.uploadDissabled = true
                        let formData = new FormData();
                        formData.append("file", this.map.file);
                        formData.append("id", this.map.id);
                        this.$http.post(Api.uploadTaskBook, formData).then((res) => {
                            this.uploadDissabled = false
                            if (res.data.status == "200") {
                                this.logInfoModel = true
                                this.logInfo = res.data.data
                                this.query()
                            } else {
                                this.$Message.error(res.data.msg);
                            }
                            this.map={}
                            this.fileTrue = false
                            this.uploadEdit=false
                        }).catch(e => {
                            console.log(e);
                            this.uploadEdit=false
                            this.map={}
                            this.uploadDissabled = false
                            this.$Message.error("导入失败！请检查导入文档的格式是否正确");
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })

            },
            uploadAcc() {
                if (this.selectId == null || this.selectId === ''|| this.selectId === undefined) {
                    this.$Message.error('请先选择任务书')
                } else {
					// if (!this.buttonDisabled) {
					// 	this.$Message.error('请先选择任务书1111')
					// } else {
						this.map.id = this.selectId
						this.uploadEdit = true
					// }
                    
                }
            },
            download() {
                window.open('任务书导入模板.xlsx','_blank')
            },
            close1() {
                this.fileTrue = false
                this.map ={}
                this.uploadEdit = false
                this.query()
            },

            exportExcel() {
                if (this.selectId == null || this.selectId === '') {
                    this.$Message.error('请先选择任务书')
                    return
                }
                this.exportLoading = true
                this.$http.get(Api.exportTaskBook+'/'+this.selectId, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = this.taskBookName+".xlsx" //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                    this.exportLoading = false
                })
            },

            submit1(name) {
                if (this.pageStatus.sending) return
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.$Modal.confirm({
                            title: '提示',
                            content: '<p>是否要提交？</p>',
                            onOk: () => {
                                let url = this.updateUrl;
                                this.pageStatus.sending = true
                                let successHandle = (res) => {
                                    if (res.data.status === 200) {
                                        this.$Message.success('修改成功');
                                        this.onCancel()
                                        this.query()
                                    } else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                    }
                                    this.pageStatus.sending = false
                                }
                                let failedHandle = e => {
                                    this.$Message.error('修改失败')
                                    this.pageStatus.sending = false
                                }
                                this.$http.put(url, this.dataToView).then(successHandle).catch(failedHandle)
                            },
                            onCancel: () => {
                            }
                        });
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            onCancel(){
                this.dataToView = {}
                this.model1= false
                this.buttonDisabled = false
            },


            async getRoleUsers(row){
                let data = {};
                data.fromPage = 1;
                data.pageSize = 100;
                if (row.belongOrgId) {
                    data.orgId = row.belongOrgId;
                }
				if (row.assessmentType == '1' ) {
					await this.$http.get(Api.queryUserInRole, {params : {
					        ...data,
					        //二级集团安全管理人员角色
					        roleId:'0071a248d8524d3db02805c3f3d21ce1',
					    }
					}).then(res => {
					    this.dictMap['saAppUserids'] = res.data.data;
					})
				} else if (row.assessmentType == '2' ) {
					await this.$http.get(Api.queryUserInRole, {params : {
					        ...data,
					        //二级集团环保管理人员角色
					        roleId:'8d2f1959dbfd437b88aebe04d50b4edf',
					    }
					}).then(res => {
					    this.dictMap['enAppUserids'] = res.data.data;
					})
				}
               await this.$http.get(Api.queryTaskBookType+ row.id).then((res) => {
                    if (res.data.data && res.data.data.length>0) {
                    	this.model3 = true
                    } else {
						this.$Message.error({
						    content: '任务书尚未进行任务分解，不可上报！',
						    duration: 4
						});
					}
                })
            },
            reportInfo(row) {
                if (row.applyUserId) {
                    this.$Modal.confirm({
                        title: '提示',
                        content: '<p>是否要提交？</p>',
                        onOk: () =>{
                            let user = sessionStorage('userId').getObject('userId')
                            this.loading = true;
                            let data = {
                                key: "taskBookApply",
                                createUserId: user.userId,
                                userName: user.userName,
                                workId: row.id,
                                type:"taskBookApply",
                                formKey: "taskBookApproval",
                                user1: row.applyUserId,
                            };
                            this.$http.post(Api.submit, data).then(function (res) {
                                this.loading = false;
                                this.$Message.success({
                                    content: '上报成功',
                                    duration: 4
                                });
                                this.model3 = false
                                this.query();
                            }, function (err) {
                                this.loading = false;
                                this.model3 = false
                                this.$Message.error({
                                    content: '上报失败',
                                    duration: 4
                                });
                            });
                        } ,
                        onCancel: () => {
                        }
                    });
                } else {
                    this.$Message.error({
                        content: '审批人不能为空',
                        duration: 4
                    });
                }
            },
            showHistory(row) {
                this.model4 = true;
                this.loading2 = true;
                this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
                    this.history = res.data;
                    this.loading2 = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },

        },
        watch: {
			'$route.name': function () {
			    this.reset()
			}
		},
    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }

</style>